﻿using Configs;
using Utils;

namespace Modules.Game.Roles
{
    /// <summary>
    ///     英雄 Model 数据
    /// </summary>
    public class HeroModel : Singleton<HeroModel>
    {
        private readonly int _heroKey = HeroConfig.HeroKeyDefault;

        /// <summary>
        ///     英雄数据
        /// </summary>
        public HeroData Data;

        private HeroModel()
        {
            ResetData();
        }

        private void InitHeroData()
        {
            Data = HeroConfig.HeroDatas[_heroKey];

            var skillKeys = Data.SkillKeys;
            foreach (var skillKey in skillKeys)
            {
                var skillData = SkillConfig.SkillDatas[skillKey];
                skillData.Cd = 0.0f;

                // 技能攻击伤害 = 技能攻击百分比属性 * 英雄攻击属性
                skillData.Attr.Atk = SkillConfig.SkillDatas[skillData.Id].Attr.Atk * Data.Attr.Atk;

                Data.SkillDatas.Add(skillData);
            }
        }

        public void ResetData()
        {
            InitHeroData();
        }

        /// <summary>
        ///     每帧刷新
        /// </summary>
        /// <param name="dt"></param>
        public void UpdateFrame(float dt)
        {
            var skillDatas = Data.SkillDatas;

            for (var i = 0; i < skillDatas.Count; i++)
            {
                var skillData = skillDatas[i];

                if (skillData.Cd > 0) skillData.Cd -= dt;
                if (skillData.Cd < 0) skillData.Cd = 0;

                skillDatas[i] = skillData;
            }
        }

        /// <summary>
        ///     每秒刷新
        /// </summary>
        public void UpdateSecond()
        {
            if (Data.Attr.CurHp < Data.Attr.TotalHp) Data.Attr.CurHp++;

            if (Data.Attr.CurMp < Data.Attr.TotalMp) Data.Attr.CurMp++;
        }

        /// <summary>
        ///     被攻击
        /// </summary>
        public void OnHit(EnemyData enemyData)
        {
            // 扣减血量 = 怪物伤害值 - 英雄防守值
            if (enemyData.Attr.Atk <= Data.Attr.Def) return;

            Data.Attr.CurHp -= enemyData.Attr.Atk - Data.Attr.Def;
        }

        /// <summary>
        ///     监听技能释放
        /// </summary>
        /// <param name="order">技能下标</param>
        /// <param name="skillData">技能数据</param>
        public void OnReleaseSkill(int order, SkillData skillData)
        {
            // 减去技能消耗
            Data.Attr.CurMp -= skillData.Attr.Mp;

            skillData.Cd = skillData.Attr.Cd;
            Data.SkillDatas[order] = skillData;
        }

        /// <summary>
        ///     获取技能数据
        /// </summary>
        /// <param name="order">技能下标</param>
        /// <returns></returns>
        public SkillData GetSkillData(int order)
        {
            return Data.SkillDatas[order];
        }
    }
}